//
//  EJSHomeViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/13.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSHomeViewController.h"
#import "EJSSegmentedControl.h"
#import "EJSHomeCategoryViewController.h"
#import "EJSHomeRecommendViewController.h"
#import "EJSGoodsCategoryRequest.h"
#import "EJSSearchViewController.h"
#import "EJSGoodsListViewController.h"
#import "EJSUpgradeVipViewController.h"

#import "XOPlatformCategoryListRequest.h"

static NSString *CCellIdentifier            = @"HomeCollectionViewReuseIdentifier";

@interface EJSHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,EJSSegmentedControlDelegate>

@property (weak, nonatomic) IBOutlet EJSSegmentedControl *segmentedControl;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) NSMutableArray *categoryList;//所有一级分类
@property (strong, nonatomic) NSMutableArray *classfyViewControllers;//推荐 + 所有一级分类的viewController

@end

@implementation EJSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configOwnViews];
    [self getFirstCategory];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)configOwnViews{
    self.segmentedControl.delegate = self;
    [self reloadClassfyViewControllers];
    [self registCell];
    [self.collectionView reloadData];
    [self configNavigationRightItemWithImage:[UIImage imageNamed:@"search"]];
    
}
- (void)leftBarButtonAction:(id)sender{
    if([self userIsLogin]){
        EJSUpgradeVipViewController *upgradVipVC = [[EJSUpgradeVipViewController alloc] initWithNibName:@"EJSUpgradeVipViewController" bundle:nil];
        [self.navigationController pushViewController:upgradVipVC animated:YES];
    }
}

- (void)rightBarButtonAction:(id)sender{
    EJSSearchViewController *searchVC = [[EJSSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}


- (void)getFirstCategory{
    FlyWeakSelf
    //获取一级分类
    [[EJSGoodsCategoryRequest new] asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.categoryList = response.data;
        [weakSelf reloadClassfyViewControllers];
    } failHandler:^(BaseResponse *response) {
        
    }];
    
}



- (void)reloadClassfyViewControllers
{
    self.classfyViewControllers = [NSMutableArray array];
    NSMutableArray *categoryTitles = [NSMutableArray array];
    
    EJSHomeRecommendViewController *recommendVC = [[EJSHomeRecommendViewController alloc] init];
    [self.classfyViewControllers addObject:recommendVC];
    
    [categoryTitles addObject:@"推荐"];
    
    for (int index = 0; index < self.categoryList.count; index ++)
    {
        EJSCategoryModel *category = self.categoryList[index];
        
        EJSHomeCategoryViewController *viewController = [[EJSHomeCategoryViewController alloc] initWithNibName:@"EJSHomeCategoryViewController" bundle:nil];
        viewController.categoryId = category.categoryId;
        [self.classfyViewControllers addObject:viewController];
        [categoryTitles addObject:category.categoryName?category.categoryName:@""];
    }
    [self.segmentedControl setCategoryTitles:categoryTitles];
    self.segmentedControl.selectedIndex = 0;
    [self registCell];
    [self.collectionView reloadData];
}

- (void)registCell
{
    for (int index = 0; index < self.classfyViewControllers.count; index ++)
    {
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:[self cellReuseIdentifierForIndex:index]];
    }
}

- (NSString *)cellReuseIdentifierForIndex:(NSInteger)aIndex
{
    return [NSString stringWithFormat:@"%@_%tu",CCellIdentifier,aIndex];
}


#pragma mark - SegmentedControlDelegate
- (void)segmentedControl:(EJSSegmentedControl *)segmentedControl selectItemAtIndex:(NSUInteger)selectedIndex
{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:selectedIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}


#pragma mark - UICollectionViewDataSource|Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _categoryList.count+1;
}

- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSString *cellReuseIdentifier = [self cellReuseIdentifierForIndex:indexPath.row];
    UICollectionViewCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    
    UIViewController *viewController = [self.classfyViewControllers objectAtIndex:indexPath.item];
    if(viewController && ![viewController.view isDescendantOfView:ccell.contentView])
    {
        [ccell.contentView addSubview:viewController.view];
        
        viewController.view.translatesAutoresizingMaskIntoConstraints = NO;
        [ccell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:viewController.view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:ccell.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
        [ccell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:viewController.view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:ccell.contentView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
        [ccell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:viewController.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:ccell.contentView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
        [ccell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:viewController.view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:ccell.contentView attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
        [ccell layoutIfNeeded];
        
        [self addChildViewController:viewController];
    }
    return ccell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return collectionView.size;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetpage = scrollView.contentOffset.x/scrollView.width;
    CGFloat py = fabs((int)offsetpage - offsetpage);
    
    if ( py <= 0.3 || py >= 0.7)
    {
        return;
    }
    
    if (offsetpage - self.segmentedControl.selectedIndex > 0)
    {
        if (py > 0.55)
        {
            self.segmentedControl.selectedIndex += 1;
        }
    }
    else
    {
        if (py < 0.45)
        {
            self.segmentedControl.selectedIndex -= 1;
        }
    }
}

@end
